// @algorithm @lc id=2 lang=cpp
// @title add-two-numbers

#include <iostream>
#include <vector>
#include <string>
#include "algm/algm.h"
using namespace std;
// @test([2,4,3],[5,6,4])=[7,0,8]
// @test([0],[0])=[0]
// @test([9,9,9,9,9,9,9],[9,9,9,9])=[8,9,9,9,0,0,0,1]
/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode() : val(0), next(nullptr) {}
 *     ListNode(int x) : val(x), next(nullptr) {}
 *     ListNode(int x, ListNode *next) : val(x), next(next) {}
 * };
 */

/**
 * @brief
 * 用一个新建的链表来存从低位一直到高位相加的结果.
 * 同时注意, 比如十位有进位, 或者两个链表任何一个表的十位有值, 那么就加下去.
 * 如果某一个表有十位, 某一个表没有, 那么就建一个空的节点放上去相加即可.
 */
class Solution {
public:
    ListNode* addTwoNumbers(ListNode* l1, ListNode* l2)
    {
        int       temp;
        ListNode* sum = new ListNode(0);
        ListNode* p   = sum;
        do {
            if (l1)
                p->val += l1->val;
            if (l2)
                p->val += l2->val;

            temp = p->val / 10;
            p->val %= 10;

            if (!temp && l1->next == NULL && l2->next == NULL)
                return sum;

            p->next = new ListNode(temp);
            p       = p->next;

            if (l1->next == NULL)
                l1->next = new ListNode(0);
            if (l2->next == NULL)
                l2->next = new ListNode(0);
            l1 = l1->next;
            l2 = l2->next;
        } while (l1 || l2);
        return sum;
    }
};